package bar.dark.lee;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.fan.FanAdapter;
import bar.dark.lee.fan.FanOutActivity;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import bar.dark.lee.setting.auto.AutoCreditDateData;
import bar.dark.lee.setting.auto.AutoData;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class IntroAutoActivity extends SuperActivity
{
	private DBSQLite sql;
	
	private Button okButton;
	
	private ListView listView;
	
	private int toYear;
	private int toMonth;
	private int toDay;
	private ArrayList<AutoData> autoList;
	private ArrayList<AutoData> tempList;
	private ArrayList<String> date;

	private int autoTotalCount;
	private int autoCreditDateCount;
	
	private int [] checks;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
	
		setContentView(R.layout.intro_auto_activity);
		
		setTitle("자동이체 선택");
		
		setFindView();
		setOnClickListener();
		setData();
	}

	private void setOnClickListener()
	{
		okButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				new ShowDialog().execute(0);
			}
		});
	}

	private void setFindView()
	{
		listView = (ListView) findViewById(R.id.introAutoListView);
		okButton = (Button) findViewById(R.id.introAutoButton);
	}
	
	private void setData()
	{
		autoTotalCount = 0;
		autoCreditDateCount = 0;
		
		Calendar cal = Calendar.getInstance();
		toYear = cal.get(Calendar.YEAR);
    	toMonth = cal.get(Calendar.MONTH);
    	toDay = cal.get(Calendar.DAY_OF_MONTH);
		
		Intent intent = getIntent();
		autoList = intent.getParcelableArrayListExtra(IntroActivitiy.INTRO_AUTO_DATA); 
		
		tempList = new ArrayList<AutoData>();
		date = new ArrayList<String>();
		
		setAutoAllData();
		
		checks = new int[tempList.size()];
		
		for (int i = 0; i < tempList.size(); i++)
		{
			checks[i] = tempList.get(i).getCheckBox();
		}
		
		if (tempList.size() <= 0)
		{
			Intent intentData = new Intent();
			intentData.putExtra(IntroActivitiy.RESULT_AUTO_COUNT, autoTotalCount);
			setResult(Activity.RESULT_OK, intent);
			finish();
		}
		
		IntroAutoAdapter adapter = new IntroAutoAdapter(this, R.layout.list_item_intro_auto, tempList);
		listView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}
	
	private void setAutoAllData()
	{
		for (int i = 0; i < autoList.size(); i++)
		{
			AutoData data = autoList.get(i);
			
			setAutoData(data);
		}
	}
	
	private void setAutoData(AutoData data)
	{
		String toDate = BDUtil.getDateDB(toYear, toMonth+1, toDay);
		String signDate = data.getSigndate();
		
		int [] toDateArr = BDUtil.getDateSet(toDate);
		int [] signDateArr = BDUtil.getDateSet(signDate);
		
		int tempYear = toDateArr[0] - signDateArr[0];
		int tempMonth = toDateArr[1] - signDateArr[1];
		
		tempMonth = (tempYear * 12) + tempMonth;
		
		int firstMonth = 0;
		
		// 할부일경우 체크
		if (data.getKind().equals("2"))
		{
			firstMonth = setCheckDateCountData(data, tempMonth);;
		}
		
		for (int j = tempMonth-1; j >= firstMonth; j--)
		{
			setArrayAutoData(data, j);
		}
		
//		for (int j = firstMonth; j < tempMonth; j++)
//		{
//			setArrayAutoData(data, tempMonth-(j+1));
//		}
	}

	private void setArrayAutoData(AutoData data, int j)
	{
		Calendar cal = Calendar.getInstance();
		
		for (int i = 0; i < j; i++)
		{
//			cal.roll(Calendar.MONTH, false);
			cal.add(Calendar.MONTH, -1);
		}
		
		int dbYear = cal.get(Calendar.YEAR);
		int dbMonth = cal.get(Calendar.MONTH);
		int dbDay = Integer.parseInt(data.getAutodate());
		
		String dbDate = BDUtil.getDateDB(dbYear, dbMonth+1, dbDay);
		String toDate = BDUtil.getDateDB(toYear, toMonth+1, toDay);
		
		if (Integer.parseInt(dbDate) > Integer.parseInt(toDate))
		{
			return;
		}
		
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		int day = Integer.parseInt(data.getAutodate());
		
		AutoData tempData = new AutoData();
		
//		tempData.setTempDate(BDUtil.getDateDB(year, month, day));
		
		if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) >= day)
		{
			tempData.setTempDate(BDUtil.getDateDB(year, month, day));
		}
		else
		{
			tempData.setTempDate(BDUtil.getDateDB(year, month, cal.getActualMaximum(Calendar.DAY_OF_MONTH)));
		}
		
		tempData.setId(data.getId());
		tempData.setName(data.getName());
		tempData.setCategory(data.getCategory());
		tempData.setMoney(data.getMoney());
		tempData.setMoneytype(data.getMoneytype());
		tempData.setAutodate(data.getAutodate());
		tempData.setSigndate(data.getSigndate());
		tempData.setMoneykind(data.getMoneykind());
		tempData.setMemo(data.getMemo());
		tempData.setKind(data.getKind());
		
		tempList.add(tempData);
	}
	
	private void setAutoUpdateData()
	{
		for (int i = 0; i < tempList.size(); i++)
		{
			AutoData data = tempList.get(i);
			
			if (checks[i] == 1)
			{
				setAutoTempData(data);
				
				setUpdateAutoBank(data);
			}
		}
	}
	
	private void setAutoTempData(AutoData tempData)
	{
		String type = "";
		// 지출, 수입 플래그
		int flag = 0;
		
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("category", tempData.getCategory());
		
		if (tempData.getMoneytype().equals("1"))
		{
			if (tempData.getKind().equals("1"))
			{
				map.put("type", BDConstents.BANK_TYPE);
				map.put("outmoney", tempData.getMoney());
				
				setBankOutData(tempData);
				
				type = BDConstents.BANK_TYPE;
				flag = 0;
			}
			else if (tempData.getKind().equals("2"))
			{
				map.put("type", BDConstents.CREDIT_TYPE);
				map.put("postmoney", tempData.getMoney());
				
				setCreditOutData(tempData);
				
				type = BDConstents.CREDIT_TYPE;
				flag = 0;
			}
		}
		else if (tempData.getMoneytype().equals("2"))
		{
			map.put("type", BDConstents.BANK_TYPE);
			map.put("inmoney", tempData.getMoney());
			
			setBankInData(tempData);
			
			type = BDConstents.BANK_TYPE;
			flag = 1;
		}
		
		String memo = tempData.getName();
		
		if (signCount!= -1 && monthCount != -1)
		{
			memo = memo + " " + monthCount + "개월 할부중 " + signCount + "회차";
		}
		
		if (tempData.getMemo() != null)
		{
			memo = memo + "\n" + tempData.getMemo();
		}
		
		map.put("memo", memo);
		
		map.put("moneykind", tempData.getMoneykind());
		
		map.put("date", tempData.getTempDate());
		
		sql.insert(this, map, "in_out");
		
		// 잔액을 입력한다.
		BalanceQuery balace = new BalanceQuery(superContext);
		balace.setBalance(type, tempData.getMoneykind());
		
		autoTotalCount++;
	}
	
	/**
	 * auto_bank 테이블의 마지막 이체 저장 날짜를 갱신한다.
	 * @param id
	 */
	private void setUpdateAutoBank(AutoData data)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("signdate", data.getTempDate());
		
		String [] whereArgs = new String[]{data.getId()};
		
		sql.update(this, "auto_bank", map, "id = ?", whereArgs);
		
		if (data.getKind().equals("2"))
		{
			setCheckDeleteData(data);
		}
	}
	
	private int creditDateCheckCount = 0;
	/**
	 * 할부 카운트를 체크해서 몇번 빠질 것인지 숫자를 정한다.
	 * @param data 
	 * @param tempMonth 
	 */
	private int setCheckDateCountData(AutoData data, final int tempMonth)
	{
		creditDateCheckCount = 0;
		
		sql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				AutoCreditDateData dateData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					dateData = new AutoCreditDateData();
					
					dateData.setId(c.getInt(idIdx) + "");
					dateData.setName(c.getString(nameIdx));
					dateData.setMonthcount(c.getInt(monthcountIdx) + "");
					dateData.setSigncount(c.getInt(signcountIdx) + "");
					dateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
				
				if (dateData != null)
				{
					int signcount = Integer.parseInt(dateData.getSigncount());
					int monthcount = Integer.parseInt(dateData.getMonthcount());
					
					if (tempMonth > (monthcount - signcount))
					{
						creditDateCheckCount = tempMonth - (monthcount - signcount);
					}
				}
			}
		});
		
		return creditDateCheckCount;
	}
	
	/**
	 * 할부일경우 할부가 끝나면 데이터를 지워준다.
	 * @param data
	 */
	private void setCheckDeleteData(final AutoData data)
	{
		sql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				AutoCreditDateData dateData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					dateData = new AutoCreditDateData();
					
					dateData.setId(c.getInt(idIdx) + "");
					dateData.setName(c.getString(nameIdx));
					dateData.setMonthcount(c.getInt(monthcountIdx) + "");
					dateData.setSigncount(c.getInt(signcountIdx) + "");
					dateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
				
				if (dateData != null)
				{
					int monthcount = Integer.parseInt(dateData.getMonthcount());
					int signcount = Integer.parseInt(dateData.getSigncount());
					
					if (signcount >= monthcount)
					{
						String [] whereArgs = new String[]{data.getId()};
						sql.delete(IntroAutoActivity.this, "auto_bank", "id = ?", whereArgs);
						
						String [] whereArgs2 = new String[]{dateData.getId()};
						sql.delete(IntroAutoActivity.this, "auto_credit_date", "id = ?", whereArgs2);
						
						autoCreditDateCount++;
					}
				}
			}
		});
	}

	private void setBankInData(final AutoData data)
	{
		sql.selectMapTile(this, "SELECT id, money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneykind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money + Integer.parseInt(data.getMoney());
				money = money.add(new BigDecimal(data.getMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				sql.update(IntroAutoActivity.this, "bankbook", map, "id = ?", whereArgs);
			}
		});
		
		setTotalMoney(true, data);
	}

	private void setBankOutData(final AutoData data)
	{
		sql.selectMapTile(this, "SELECT id, money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneykind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money - Integer.parseInt(data.getMoney());
				money = money.subtract(new BigDecimal(data.getMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				sql.update(IntroAutoActivity.this, "bankbook", map, "id = ?", whereArgs);
			}
		});
		
		setTotalMoney(false, data);
	}

	private void setTotalMoney(final boolean isInMoney, final AutoData data)
	{
		sql.selectMapTile(this, "SELECT money FROM total_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				if (isInMoney)
				{
//					money = money + Integer.parseInt(data.getMoney());
					money = money.add(new BigDecimal(data.getMoney()));
				}
				else
				{
//					money = money - Integer.parseInt(data.getMoney());
					money = money.subtract(new BigDecimal(data.getMoney()));
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				sql.update(IntroAutoActivity.this, "total_money", map, null, null);
			}
		});
	}

	private int monthCount = -1;
	private int signCount = -1;
	
	private void setCreditOutData(final AutoData data)
	{
		monthCount = -1;
		signCount = -1;
		
		sql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneykind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money + Integer.parseInt(data.getMoney());
				money = money.add(new BigDecimal(data.getMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				sql.update(IntroAutoActivity.this, "credit_card", map, "id = ?", whereArgs);
			}
		});
		
		sql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				AutoCreditDateData dateData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					dateData = new AutoCreditDateData();
					
					dateData.setId(c.getInt(idIdx) + "");
					dateData.setName(c.getString(nameIdx));
					dateData.setMonthcount(c.getInt(monthcountIdx) + "");
					dateData.setSigncount(c.getInt(signcountIdx) + "");
					dateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
				
				if (dateData != null)
				{
					monthCount = Integer.parseInt(dateData.getMonthcount());
					signCount = Integer.parseInt(dateData.getSigncount()) + 1;
					
					HashMap<String, String> map = new HashMap<String, String>();
					
					int count = Integer.parseInt(dateData.getSigncount()) + 1;
					
					map.put("signcount", count + "");
					
					String [] whereArgs = new String[]{dateData.getId()};
					sql.update(IntroAutoActivity.this, "auto_credit_date", map
							, "id = ?", whereArgs);
				}
			}
		});
	}

	private class IntroAutoAdapter extends ArrayAdapter<AutoData>
	{
		public IntroAutoAdapter(Context context, int textViewResourceId,
				ArrayList<AutoData> list)
		{
			super(context, textViewResourceId, list);
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			final AutoData data = tempList.get(position);
			
			if (v == null)
			{
				v = getLayoutInflater().inflate(R.layout.list_item_intro_auto, null);
			}
			
			TextView date = (TextView) v.findViewById(R.id.introAutoListItemDate);
			TextView kind = (TextView) v.findViewById(R.id.introAutolistItemKind);
			TextView money = (TextView) v.findViewById(R.id.introAutoListItemMoney);
			CheckBox checkBox = (CheckBox) v.findViewById(R.id.introAutoListItemCheckBox);
			
			date.setText(data.getTempDate());
			kind.setText(data.getName());
			money.setText(BDUtil.getWon(data.getMoney()));
			
			if (data.getMoneytype().equals("1"))
			{
				money.setTextColor(Color.RED);
				money.setText("-" + BDUtil.getWon(data.getMoney()) + shape);
			}
			else if (data.getMoneytype().equals("2"))
			{
				money.setTextColor(Color.BLUE);
				money.setText("+" + BDUtil.getWon(data.getMoney()) + shape);
			}
			
			if (checks[position] == 0)
			{
				checkBox.setChecked(false);
			}
			else
			{
				checkBox.setChecked(true);
			}
			
//			checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
//			{
//				@Override
//				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
//				{
//					if (isChecked)
//					{
//						data.setCheckBox(1);
//					}
//					else
//					{
//						data.setCheckBox(0);
//					}
//				}
//			});
			
			checkBox.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					CheckBox cb = (CheckBox) v;
					
					if (cb.isChecked())
					{
						checks[position] = 1;
					}
					else
					{
						checks[position] = 0;
					}
				}
			});
			
			return v;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(IntroAutoActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0)
			{
				setAutoUpdateData();
				return 0;
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				Intent intent = new Intent();
				intent.putExtra(IntroActivitiy.RESULT_AUTO_COUNT, autoTotalCount);
				intent.putExtra(IntroActivitiy.RESULT_AUTO_CREATE_DATE_COUNT, autoCreditDateCount);
				setResult(Activity.RESULT_OK, intent);
				finish();
				
//				AlertDialog.Builder builder = new AlertDialog.Builder(IntroAutoActivity.this);
//				builder.setTitle("알림");
//				builder.setMessage("자동이체가 " + autoTotalCount + "건이 처리 되었습니다.");
//				builder.setIcon(android.R.drawable.ic_dialog_info);
//				builder.setNegativeButton("확인", new DialogInterface.OnClickListener()
//				{
//					@Override
//					public void onClick(DialogInterface dialog, int which)
//					{
//						Intent intent = new Intent(IntroAutoActivity.this, MainActivity.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//						startActivity(intent);
//						finish();
//					}
//				});
//				builder.show();
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_AUTOBANK);
		startActivity(intent);
	}
}
